package com.byCreation.Profile;





import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.byCreation.Control.Control;
import com.byCreation.t_globe.LoginActivity;
import com.byCreation.t_globe.MainActivity;
import com.byCreation.t_globe.R;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import FileIO.DeleteFile;
import FileIO.ReadWrite;
import FileIO.SaveImage;
import Parser.HttpGetJson;
import Parser.SendToBD;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MyprofileActivity extends Activity implements OnClickListener{

	

		//======================Image===============================
		private ImageView Image_profile;
		
		
		//====================Browse================
		 private static final int SELECT_PICTURE = 1;
		 private String selectedImagePath="";
		 
		 
		 //===================Edittext
		 private EditText edt_name,edt_location,edt_bio,edt_email,edt_phone,edt_gender;
		 
		// ===============GoogleAnalytics==============
			private GoogleAnalytics mGaInstance;
			private Tracker mGaTracker;
			// =============================================
			// ===================================googleAnalytics=============================
		@Override
		public void onStart() {
			super.onStart();
			// The rest of your onStart() code.
			EasyTracker.getInstance().activityStart(this); // Add this method.
			mGaTracker.sendView("Myprofile Screen");

		}

		@Override
		public void onStop() {
			super.onStop();
			// The rest of your onStop() code.
			EasyTracker.getInstance().activityStop(this); // Add this method.

		}

		// =====================================================================	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_myprofile);
		
		// =============================GoogleAnalytics=========================
				mGaInstance = GoogleAnalytics.getInstance(this);
				mGaTracker = mGaInstance.getTracker(Control.IDGoogleanalytics);	

		final ImageView img_close = (ImageView) findViewById(R.id.img_close);
		 img_close.setOnClickListener(new OnClickListener() {
             public void onClick(View v) {
                 // Perform action on click   
            	 finish();
               
             }
         });
		 
		 final Button btn_save = (Button) findViewById(R.id.btn_save);
		 btn_save.setOnClickListener(new OnClickListener() {
             public void onClick(View v) {
                 // Perform action on click 
            	 Toast.makeText(MyprofileActivity.this, "Save Profile", 500).show();
            	 Log.e("TG","selectedImagePath:"+selectedImagePath);
            	 
            	 
            	 final String strUrlServer = "http://api.bycreation.co.th/API_02/profile/uploadFile.php";
 		    	
            	 if(!selectedImagePath.equals(""))
            	 new UploadFileAsync().execute(selectedImagePath,strUrlServer);
            	 
            	 //finish();
 		    	 
 		    	
 		    	 new Save_MyProfile().execute();
               
             }
         });
	
		
		
		 
		 
		 
		 edt_name=(EditText)findViewById(R.id.edt_name);
		 edt_location=(EditText)findViewById(R.id.edt_location);
		 edt_bio=(EditText)findViewById(R.id.edt_bio);
		 edt_email=(EditText)findViewById(R.id.edt_email);
		 edt_phone=(EditText)findViewById(R.id.edt_phone);
		 edt_gender=(EditText)findViewById(R.id.edt_gender);
		 
		 
		//======================image========================
		
		Image_profile=(ImageView)findViewById(R.id.Image_profile);
		Image_profile.setOnClickListener(this);
		
		
		new Load_Profile().execute();
		
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	
		
		if(v.getId()==R.id.Image_profile)
		{
			  Intent intent = new Intent();
              intent.setType("image/*");
              intent.setAction(Intent.ACTION_GET_CONTENT);
              startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);

		}
		
		
	}
	
	
	private  boolean iSNewUpload=false;
	
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
        
		try {
			
				if (resultCode == RESULT_OK) {
		            if (requestCode == SELECT_PICTURE) {
		                Uri selectedImageUri = data.getData();
		                selectedImagePath = getPath(selectedImageUri);
		                
		               Bitmap resized = decodeSampledBitmapFromPath(selectedImagePath, 500, 500);
		               Image_profile.setImageBitmap(getCroppedBitmap(resized));
		                
		               
		               iSNewUpload=true;
		            }
		        }
				
					
				
		
		} catch (Exception e) {
			Toast.makeText(MyprofileActivity.this,e.toString(),2000).show();
		}
    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    
    
    
    
    public Bitmap getCroppedBitmap(Bitmap bitmap ) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        // canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        if(bitmap.getWidth()>bitmap.getHeight())
        canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,bitmap.getHeight() /2, paint);
        else
        	 canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,bitmap.getWidth() /2, paint);
        
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        //Bitmap _bmp = Bitmap.createScaledBitmap(output, 60, 60, false);
        //return _bmp;
        return output;
    }

    public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth,
            int reqHeight) {
 
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
 
        options.inSampleSize = calculateInSampleSize(options, reqWidth,reqHeight);
 
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        Bitmap bmp = BitmapFactory.decodeFile(path, options);
        return bmp;
        }

    public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
 
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
 
        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
             }
         }
         return inSampleSize;
        }


    public static Bitmap getBitmapFromURL(String src) {
        try {
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    
    
    
    //=======UpLoadFile
    public static final int DIALOG_UPLOAD_PROGRESS = 0;
    private ProgressDialog mProgressDialog;

    public void showSuscess(String resServer)
    {
    	
        /** Get result from Server (Return the JSON Code)
         * StatusID = ? [0=Failed,1=Complete]
         * Error	= ?	[On case error return custom error message]
         * 
         * Eg Upload Failed = {"StatusID":"0","Error":"Cannot Upload file!"}
         * Eg Upload Complete = {"StatusID":"1","Error":""}
         */
    	
        /*** Default Value ***/
    	String strStatusID = "0";
    	String strError = "Unknow Status!";
    	
    	try {  		
    		
			JSONObject c = new JSONObject(resServer);
			ImageFileName = c.getString("filename");
        	
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	
//
//    	try {  		
//    		
//			JSONObject c = new JSONObject(resServer);
//        	strStatusID = c.getString("StatusID");
//        	strError = c.getString("Error");
//		} catch (JSONException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//    	
//    	
//    	// Prepare Status
//		if(strStatusID.equals("0"))
//		{
//			AlertDialog.Builder ad  = new AlertDialog.Builder(this);
//			ad.setTitle("Error!");
//			ad.setIcon(android.R.drawable.btn_star_big_on);
//            ad.setMessage(strError);
//            ad.setPositiveButton("Close", null);
//            ad.show();
//		}
//		else
//		{
//			Toast.makeText(MyprofileActivity.this, "Upload file Successfully", Toast.LENGTH_SHORT).show();
//		}
    	new Load_ImageName().execute();
		
    }
    
    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_UPLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Uploading file.....");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setCancelable(true);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    }
    
    // http://api.bycreation.co.th/API_02/profile/myfile/
    
    private String ImageFileName="";
    public class UploadFileAsync extends AsyncTask<String, Void, Void> {

    	String resServer;
    	
        protected void onPreExecute() {
        	super.onPreExecute();
        	showDialog(DIALOG_UPLOAD_PROGRESS);
        }

        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub

        	int bytesRead, bytesAvailable, bufferSize;
    		byte[] buffer;
    		int maxBufferSize = 1 * 1024 * 1024;
    		int resCode = 0;
        	String resMessage = "";

        	String lineEnd = "\r\n";
        	String twoHyphens = "--";
        	String boundary =  "*****";
		   

    	    String strSDPath = params[0];
    	    String strUrlServer = params[1];
    	    
    	    
    	    
    	    
    		try {
    			/** Check file on SD Card ***/
    			File file = new File(strSDPath);
    			//ImageFileName= file.getName();
    			if(!file.exists())
    			{
    				resServer = "{\"StatusID\":\"0\",\"Error\":\"Please check path on SD Card\"}";
    				return null;
    			}
    			
    			FileInputStream fileInputStream = new FileInputStream(new File(strSDPath));

    			URL url = new URL(strUrlServer);
    			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    			conn.setReadTimeout(10000);
    			conn.setConnectTimeout(15000);
    			conn.setDoInput(true);
    			conn.setDoOutput(true);
    			conn.setUseCaches(false);
    			conn.setRequestMethod("POST");

    			conn.setRequestProperty("Connection", "Keep-Alive");
    			conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
    			//conn.setRequestProperty("filename","maxgunner.png");

    			
    			List<NameValuePair> parametor = new ArrayList<NameValuePair>();
    			//parametor.add(new BasicNameValuePair("username","maxgunner"));
    			
    			
    			OutputStream os = conn.getOutputStream();
    			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    			writer.write(getQuery(parametor));
    			
    			Log.e("TG","strSDPath:"+strSDPath);
    			
    			
    			DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
    			outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    			outputStream.writeBytes("Content-Disposition: form-data; name=\"filUpload\";filename=\""
    							+ strSDPath + "\"" + lineEnd);
    			outputStream.writeBytes(lineEnd);
    			outputStream.writeBytes(getQuery(parametor));
    			

    			bytesAvailable = fileInputStream.available();
    			bufferSize = Math.min(bytesAvailable, maxBufferSize);
    			buffer = new byte[bufferSize];

    			// Read file
    			bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    			while (bytesRead > 0) {
    				
    				Log.e("bytesRead", "bytesRead");
    				outputStream.write(buffer, 0, bufferSize);
    				bytesAvailable = fileInputStream.available();
    				bufferSize = Math.min(bytesAvailable, maxBufferSize);
    				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    			}

    			outputStream.writeBytes(lineEnd);
    			outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    			// Response Code and  Message
    			resCode = conn.getResponseCode();
    			if(resCode == HttpURLConnection.HTTP_OK)
    			{
                    InputStream is = conn.getInputStream();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    
                    int read = 0;
                    while ((read = is.read()) != -1) {
                          bos.write(read);
                    }
                    byte[] result = bos.toByteArray();
                    bos.close();
                         
                    resMessage = new String(result);
                    
    			}
    			
    			Log.d("resCode=",Integer.toString(resCode));
    			Log.d("resMessage=",resMessage.toString());

    			fileInputStream.close();
    			outputStream.flush();
    			outputStream.close();
    			
    			resServer = resMessage.toString();
    			
    			
    		} catch (final Exception ex) {
    			// Exception handling
    			runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						Toast.makeText(MyprofileActivity.this, ex.toString(),2000);
					}
				});
    			
    			return null;
    		}
    		
    		return null;
        }

        @SuppressWarnings("deprecation")
		protected void onPostExecute(Void unused) {
        	
			Toast.makeText(MyprofileActivity.this, resServer,2000);
			
			
			
			try {
					
        	showSuscess(resServer);
            dismissDialog(DIALOG_UPLOAD_PROGRESS);
            removeDialog(DIALOG_UPLOAD_PROGRESS);
            
            
            
            
            
			} catch (Exception e) {
				// TODO: handle exception
			}
            
            
        }

    }
   
    private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (NameValuePair pair : params)
        {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }

        return result.toString();
    }
    
    
    class Load_Profile extends AsyncTask<Object, Integer, Object> {

	    private ProgressDialog mProgressDialog;
		private String desc,name,email,facebookid,img,fb_img_path,location,bio,phone_no,gender;
		private boolean Cancle=false;

			  @Override
			protected void onCancelled() {
				// TODO Auto-generated method stub
				  Cancle=true;
				super.onCancelled();
			}
		
		@SuppressWarnings("null")
		@Override
		protected Object doInBackground(Object... params) {

			try {
				JSONObject jsonObj=null;
				jsonObj = new JSONObject(HttpGetJson.GetJson(Control.getAPI_LoadProfile(Control.UserName),Control.user,Control.pass));
				
				desc=jsonObj.getString("result");
		  
				
				JSONArray Jsonarray_profile=jsonObj.getJSONArray("profile");
				 for (int i = 0; i <Jsonarray_profile.length(); i++)
				 { 
					 
					 JSONObject jsonObj_data=Jsonarray_profile.getJSONObject(i);

					 Log.e("TG","name:"+jsonObj_data.getString("name"));
					 Log.e("TG","email:"+jsonObj_data.getString("email"));
					 Log.e("TG","facebookid:"+jsonObj_data.getString("facebookid"));
					 Log.e("TG","img:"+jsonObj_data.getString("img"));
					 Log.e("TG","fb_img_path:"+jsonObj_data.getString("fb_img_path"));
					 Log.e("TG","location:"+jsonObj_data.getString("location"));
					 Log.e("TG","bio:"+jsonObj_data.getString("bio"));
					 Log.e("TG","phone_no:"+jsonObj_data.getString("phone_no"));
					 Log.e("TG","gender:"+jsonObj_data.getString("gender"));

					img=jsonObj_data.getString("img"); 
					name=jsonObj_data.getString("name");
					email=jsonObj_data.getString("email");
					location=jsonObj_data.getString("location");
					bio=jsonObj_data.getString("bio");
					phone_no=jsonObj_data.getString("phone_no");
					gender=jsonObj_data.getString("gender");
					 

					 
				 }
				
		    
		    
				
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (final Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					Toast.makeText(MyprofileActivity.this, e.toString(),2000).show();
				}
			});
			
		}
			

		
				 
			return null;
		}

		@Override
		protected void onPreExecute() {

			 //=====================ProgressDialog==========================
	        mProgressDialog = new ProgressDialog(MyprofileActivity.this);
	        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);         
	        mProgressDialog.setMessage("Loading......");                       
	    	mProgressDialog.setCancelable(true);
		
			
			if(mProgressDialog!=null)
				mProgressDialog.show();
			
			
			
			super.onPreExecute();
		}

		@Override
		public void onProgressUpdate(Integer... progress) {

			Log.e("star", "progressupdate");
			
			
		}

		@Override
		protected void onPostExecute(Object result) {
			Toast.makeText(MyprofileActivity.this, desc, 800).show();

		if(!Cancle)
		{
			
//			Picasso.with(MyprofileActivity.this).load(img)
//			.placeholder(R.drawable.profile_pic_default)
//			.error(R.drawable.profile_pic_default)
//			.into(Image_profile);
			
			 edt_name.setText(name);
			 edt_location.setText(location);
			 edt_bio.setText(bio);
			 edt_email.setText(email);
			 edt_phone.setText(phone_no);
			 edt_gender.setText(gender);
             
			
			
			
		}

			if(mProgressDialog!=null)
				mProgressDialog.hide();
			
			
			

			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					try {
						
						
						
						Log.e("Picasso", "=========Picasso() ==========");
						
						if(Control.Img_profile.equals(""))
						{
							Image_profile.setImageResource(R.drawable.btn_menu_top_righ);

						}
						else
						{
							Bitmap myBitmap = BitmapFactory.decodeFile(Control.Img_profile_Path);
							Image_profile.setImageBitmap(myBitmap);
						}
						
						
						
						} catch (Exception e) {
							Image_profile.setImageResource(R.drawable.btn_menu_top_righ);
						}
			
				}
			});
			
			
		}
		
		
		
		
		

	}
    
    
    
    
    
    
   
    
    class Load_ImageName extends AsyncTask<Object, Integer, Object> {

	    private ProgressDialog mProgressDialog;
		private String title,content,images,date,link,result,desc;
		private boolean Cancle=false;
			
			
			  @Override
			protected void onCancelled() {
				// TODO Auto-generated method stub
				  Cancle=true;
				super.onCancelled();
			}
		
		@SuppressWarnings("null")
		@Override
		protected Object doInBackground(Object... params) {

			
			Log.e("TG","img_name:"+ImageFileName+" UserName:"+Control.UserName);
			String respone="";

			try {
				
				
				 ArrayList<String> arrayList_parametor=new ArrayList<String>();
				 ArrayList<String> arrayList_value=new ArrayList<String>();
				
				 arrayList_parametor.add("img_name");
				 arrayList_value.add(ImageFileName);
					
				 arrayList_parametor.add("username");
				 arrayList_value.add(Control.UserName);
		
				 SendToBD sd=new SendToBD(MyprofileActivity.this);
				 respone=sd.send(
							Control.user, 
							Control.pass, 
							Control.getAPI_UpdateImageProfile(),
							arrayList_parametor,
							arrayList_value);
					
					JSONObject jsonObj;
					jsonObj = new JSONObject(respone);
					
					
					Log.e("tg","result="+jsonObj.getString("result"));
					ImageFileName=jsonObj.getString("img");
				
		    
					DeleteFile.Deletefolder(new File(Control.Img_profile_Path));
				    SaveImage.storeImage(SaveImage.getCroppedBitmap(SaveImage.getBitmapFromURL(ImageFileName)),MyprofileActivity.this);

					
					
		    
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
				 
			return null;
		}

		@Override
		protected void onPreExecute() {


			super.onPreExecute();
		}

		@Override
		public void onProgressUpdate(Integer... progress) {

			Log.e("star", "progressupdate");
						
		}

		@Override
		protected void onPostExecute(Object result) {
			
		if(!Cancle)
		{
			Log.e("TG", "ImageFileName:"+ImageFileName);
			Toast.makeText(MyprofileActivity.this, desc, 800).show();
			try {
				
				
				
				Log.e("Picasso", "=========Picasso() ==========");
				
				if(Control.Img_profile.equals(""))
				{
					Image_profile.setImageResource(R.drawable.btn_menu_top_righ);

				}
				else
				{
					Bitmap myBitmap = BitmapFactory.decodeFile(Control.Img_profile_Path);
					Image_profile.setImageBitmap(myBitmap);
				}
				
				
				
				} catch (Exception e) {
					Image_profile.setImageResource(R.drawable.btn_menu_top_righ);
				}
			finish();
		}
	}
    
    
    }
    
    
    
    private String username="",name="",location="",bio="",email="",phone_no="",gender="";
    class Save_MyProfile extends AsyncTask<Object, Integer, Object> {

    	String desc="";
    	
    	boolean Cancle=false;
    	
    	
		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			Cancle=true;
			super.onCancelled();
		}

		@SuppressWarnings("null")
		@Override
		protected Object doInBackground(Object... params) {
		try {
			 ArrayList<String> arrayList_parametor=new ArrayList<String>();
			 ArrayList<String> arrayList_value=new ArrayList<String>();
			
			 arrayList_parametor.add("username");
			 arrayList_value.add(username);
				
			 arrayList_parametor.add("name");
			 arrayList_value.add(name);
			 
			 arrayList_parametor.add("location");
			 arrayList_value.add(location);
			 
			 arrayList_parametor.add("bio");
			 arrayList_value.add(bio);
			 
			 arrayList_parametor.add("email");
			 arrayList_value.add(email);
			 
			 arrayList_parametor.add("phone_no");
			 arrayList_value.add(phone_no);
			 
			 arrayList_parametor.add("gender");
			 arrayList_value.add(gender);
			
			 
			 SendToBD sd=new SendToBD(MyprofileActivity.this);
			 String respone=sd.send(
						Control.user, 
						Control.pass, 
						Control.getAPI_SaveProfile(),
						arrayList_parametor,
						arrayList_value);
				
				JSONObject jsonObj;
				jsonObj = new JSONObject(respone);
				Log.e("tg","result="+jsonObj.getString("result"));
			    
				
				if(jsonObj.getString("result").equals("success"))
				
				desc=jsonObj.getString("desc");
				
			    
			 
				
			} catch (JSONException e) {
				e.printStackTrace();
			}catch (final Exception e) {
				e.printStackTrace();
				runOnUiThread(new  Runnable() {
					public void run() {
						
						Toast.makeText(MyprofileActivity.this, e.toString(), 900).show();

						
					}
				});
				
				
			}
			
			
			
				 
			return null;
		}

		@Override
		protected void onPreExecute() {

			   mProgressDialog = new ProgressDialog(MyprofileActivity.this);
		        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);         
		        mProgressDialog.setMessage("Loading......");                       
		    	mProgressDialog.setCancelable(true);

		    	
		    	
		    	 try {username=Control.UserName;} catch (Exception e) {};
		    	 try {name=edt_name.getText().toString();} catch (Exception e) {};
		    	 try {location=edt_location.getText().toString();} catch (Exception e) {};
		    	 try {bio=edt_bio.getText().toString();} catch (Exception e) {};
		    	 try {email=edt_email.getText().toString();} catch (Exception e) {};
		    	 try {phone_no=edt_phone.getText().toString();} catch (Exception e) {};
		    	 try {gender=edt_gender.getText().toString();} catch (Exception e) {};
		    	
			
			if(mProgressDialog!=null)
				mProgressDialog.show();

			
			
			
			
			super.onPreExecute();
		}

		@Override
		public void onProgressUpdate(Integer... progress) {

			Log.e("star", "progressupdate");
			
			
		}

		
		
		
		
		
		@Override
		protected void onPostExecute(Object result) {
			
			
			if(Cancle)
			{
				
				Toast.makeText(MyprofileActivity.this, desc, 900).show();
			
			}
			finish();
			
			 if(mProgressDialog != null)
		            mProgressDialog.dismiss();
			
			
		
			 
		}

		
	}
	

    
    
    
    
    
    
}
